package com.yangl.corejava.net.support;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;

/**
 * @author hasee
 */
public class HttpManager {

    public static SSLContext getTrustAllSSLContext() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager trust = new HttpManager.CustomTrustManager();
        trustAllCerts[0] = trust;
        String algorithm = null;
        String[] algorithms = new String[]{"TLS", "SSL"};
        if (algorithm != null) {
            algorithms = algorithm.split(",");
        }

        SSLContext sc = null;
        String[] arr$ = algorithms;
        int len$ = algorithms.length;
        int i$ = 0;

        while(i$ < len$) {
            String version = arr$[i$];

            try {
                sc = SSLContext.getInstance(version);
                break;
            } catch (NoSuchAlgorithmException e) {
                ++i$;
            }
        }

        if (sc == null) {
            throw new RuntimeException("fail to get SSLContext for " + Arrays.asList(algorithms));
        } else {
            sc.init((KeyManager[])null, trustAllCerts, (SecureRandom)null);
            return sc;
        }
    }

    static class CustomTrustManager implements TrustManager, X509TrustManager {
        CustomTrustManager() {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        }
    }

}
